//
//  FeedSetViewController.m
//  Bespoke
//
//  Created by Cheng on 12/8/8.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//
#import "FeedSetViewController.h"
#import "InstagramViewController.h"
#import "AppDelegate.h"
#import "BK_Enviroment.h"
#import "AddGoogleReaderCell.h"
#import "RequestAPIFunction.h"
#import "Split.h"
#import "Crop.h"
#import "LoadingUI.h"

#define TW_X_AUTH_MODE_KEY                  @"x_auth_mode"
#define TW_X_AUTH_MODE_REVERSE_AUTH         @"reverse_auth"
#define TW_X_AUTH_MODE_CLIENT_AUTH          @"client_auth"
#define TW_X_AUTH_REVERSE_PARMS             @"x_reverse_auth_parameters"
#define TW_X_AUTH_REVERSE_TARGET            @"x_reverse_auth_target"
#define TW_X_AUTH_USERNAME                  @"x_auth_username"
#define TW_X_AUTH_PASSWORD                  @"x_auth_password"
#define TW_SCREEN_NAME                      @"screen_name"
#define TW_USER_ID                          @"user_id"
#define TW_OAUTH_URL_REQUEST_TOKEN          @"https://api.twitter.com/oauth/request_token"
#define TW_OAUTH_URL_AUTH_TOKEN             @"https://api.twitter.com/oauth/access_token"
#define OAUTH_TOKEN                         @"oauth_token"
#define OAUTH_TOKEN_SECRET                  @"oauth_token_secret"

#define POP_ALERT(_W,_X) [[[UIAlertView alloc] initWithTitle:_W message:_X delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil ] show]

#define RESPONSE_EXPECTED_SIZE 4
#define BOARDERHEIGHT 5
#define BOTTOMSAPCE 5
#define STARTING_ADDGOOGLEREADERCELL_TAG 201
#define STARTING_DELGOOGLEREADERCELL_TAG 301
#define TUMBLR_ALERTVIEW_TAG 2000000
#define TUMBLR_TEXTFIELD_TAG 3000000
#define SignOut_Tag 4000000
#define GOOGLERESULT_TAG 5000000
#define GOOGLESELECTED_TAG 6000000
#define LOADINGVIEW_TAG 10000000
#define LOADINGIMAGE_TAG 20000000

#define BOTTOMBAR_HEIGHT 43
#define GOOGLEREADERCELL_HEIGHT 55

#define GoogleFeed_TOP_AXIS_Y 240
#define PHOTO_ARROW_AXIS_X 37
#define FUNCTIONALERT_ARROW_AXIS_X 101

#define KEYWORD_TITLE @"Search Results for "

#define QUESTION_ARROW_AXIS_X 492

#define GOOGLEFEEDSEARCH_API @"http://54.235.166.43/BeSpokeAPI/RSS/GoogleFeedSearch.php"
#define UPLOADACCOUNTINFO_API @"http://54.235.166.43/BeSpokeAPI/UploadAccountInfo.php"

@implementation FeedSetViewController
@synthesize BK_En_object;
@synthesize accounts = _accounts, accountStore = _accountStore;
@synthesize SW_FaceBook,SW_Twitter,SW_Instagram,SW_Tumblr, Vw_QuestionView;
@synthesize SVw_GoogleResult,SVw_GoogleSelected, Bt_Continue, Vw_PhotoList;
@synthesize Tf_GoogleReaderSearch, AddCellTagMax, Array_AccountInfo, Vw_FunctionAlertView;
@synthesize Bt_ChangePassword, Vw_ChangePassword, Lab_yourName, Lab_yourEmail, Lab_GoogleKeyword;
@synthesize Bt_yourPhoto, Ctr_poper, Vw_SearchForFeeds, SVw_RecommendedFeeds, Bt_Setting, IVw_FeedStatus;
@synthesize delegate;

int m_DelCellAxisY = 0;
int m_AddCellTagMax = 0;
int m_ProfileImageButton = 0;
bool Feed_Status = TRUE;
bool NonFirstCheck = TRUE;

-(IBAction)ConitunePressed:(id)sender {
    NonFirstCheck = TRUE;
    [NSThread detachNewThreadSelector:@selector(threadStartAnimating) toTarget:self withObject:nil];
    [self.delegate FeedSetViewControllerDelegateDidLoadingStream:self];
}

-(void)viewDidLoad {
    
    [super viewDidLoad];
    
    Lab_yourName.text = [BK_En_object.fullName uppercaseString];
    Lab_yourEmail.text = BK_En_object.userName;
    
    SVw_GoogleResult.tag = GOOGLERESULT_TAG;
    SVw_GoogleSelected.tag = GOOGLESELECTED_TAG;
    
    //Is or not hide ChangePassword button.
    if ((self.BK_En_object.passWord!=nil)&&(![self.BK_En_object.passWord isEqualToString:@""])&&
        ([((AccountInfo *)[Array_AccountInfo objectAtIndex:0]).NS_Organization isEqualToString:@"Bespoke"]))
        Bt_ChangePassword.hidden = NO;
    
    [Bt_Continue.titleLabel setFont:[UIFont fontWithName:@"EamesCenturyModern-Regular" size:12]];
    
    
    //Check setting of Enviroment.
    if(BK_En_object.yourPhoto!=nil)
        [self.Bt_yourPhoto setImage:[BK_En_object.yourPhoto imageByScalingAndCroppingForSize:CGSizeMake(self.Bt_yourPhoto.frame.size.width, self.Bt_yourPhoto.frame.size.height)] forState:UIControlStateNormal];
    
    if(BK_En_object.FacebookFeedCheck==NO)
        SW_FaceBook.on = FALSE;
    else
        SW_FaceBook.on = TRUE;
    
    if(BK_En_object.TwitterFeedCheck==NO)
        SW_Twitter.on = FALSE;
    else
        SW_Twitter.on = TRUE;
    
    if(BK_En_object.TumblrFeedCheck==NO)
        SW_Tumblr.on = FALSE;
    else
        SW_Tumblr.on = TRUE;
    
    if(BK_En_object.InstagramFeedCheck==NO)
        SW_Instagram.on = FALSE;
    else
        SW_Instagram.on = TRUE;
    
    m_DelCellAxisY = GoogleFeed_TOP_AXIS_Y;
    
    //GoogleReader.
    if([BK_En_object.Array_GoogleReaderLink count] !=0) {
      
        for (int i=0; i<[BK_En_object.Array_GoogleReaderLink count]; i++) {
            
            AddGoogleReaderCell *Vw_GoogleReaderCell = [[[NSBundle mainBundle] loadNibNamed:@"AddGoogleReaderCell" owner:self options:nil] objectAtIndex:0];
            Vw_GoogleReaderCell.frame = CGRectMake(0, m_DelCellAxisY, Vw_GoogleReaderCell.frame.size.width, Vw_GoogleReaderCell.frame.size.height);
            
            Vw_GoogleReaderCell.Lab_GoogleReaderTitle.text = [BK_En_object.Array_GoogleTitleSelected objectAtIndex:i];
            Vw_GoogleReaderCell.Lab_GoogleReaderContent.text = [BK_En_object.Array_GoogleContentSelected objectAtIndex:i];
            Vw_GoogleReaderCell.Lab_GoogleReaderWebLink.text = [BK_En_object.Array_GoogleReaderLink objectAtIndex:i];
            
            [Vw_GoogleReaderCell.Lab_GoogleReaderTitle setFont:[UIFont fontWithName:@"EamesCenturyModern-Regular" size:11.5]];
            [Vw_GoogleReaderCell.Lab_GoogleReaderTitle setTextColor:[UIColor colorWithRed:108.0/255.0 green:109.0/255.0 blue:111.0/255.0 alpha:1.0]];
            [Vw_GoogleReaderCell.Lab_GoogleReaderContent setTextColor:[UIColor colorWithRed:163.0/255.0 green:163.0/255.0 blue:164.0/255.0 alpha:1.0]];
            
            Vw_GoogleReaderCell.Bt_icon.hidden = NO;
            Vw_GoogleReaderCell.Bt_AddGoogleReader.enabled = NO;
            
            [Vw_GoogleReaderCell.SW_GoogleReader setAlpha:1.0];
            
            //Check Switch on or off.
            if ([[BK_En_object.Array_GoogleSwitchCheck objectAtIndex:i] integerValue]==0)
                [Vw_GoogleReaderCell.SW_GoogleReader setOn:NO];
            
            //Set Action.
            [Vw_GoogleReaderCell.Bt_AddGoogleReader setImage:[UIImage imageNamed:@"Frame_Rss.png"] forState:UIControlStateNormal];
            [Vw_GoogleReaderCell.Bt_icon addTarget:self action:@selector(DelGoogleReaderPressed:) forControlEvents:UIControlEventTouchUpInside];
            [Vw_GoogleReaderCell.SW_GoogleReader addTarget:self action:@selector(SwitchPressed:) forControlEvents:UIControlEventValueChanged];
            
            //Set Tag.
            [Vw_GoogleReaderCell.Lab_GoogleReaderTitle setTag:i+STARTING_DELGOOGLEREADERCELL_TAG];
            [Vw_GoogleReaderCell.Lab_GoogleReaderContent setTag:i+STARTING_DELGOOGLEREADERCELL_TAG];
            [Vw_GoogleReaderCell.Lab_GoogleReaderWebLink setTag:i+STARTING_DELGOOGLEREADERCELL_TAG];
            [Vw_GoogleReaderCell.Bt_AddGoogleReader setTag:i+STARTING_DELGOOGLEREADERCELL_TAG];
            [Vw_GoogleReaderCell.Bt_icon setTag:i+STARTING_DELGOOGLEREADERCELL_TAG];
            [Vw_GoogleReaderCell.SW_GoogleReader setTag:i+STARTING_DELGOOGLEREADERCELL_TAG];
            [Vw_GoogleReaderCell setTag:i+STARTING_DELGOOGLEREADERCELL_TAG];
            
            [SVw_GoogleSelected addSubview:Vw_GoogleReaderCell];
            
            m_DelCellAxisY = m_DelCellAxisY + Vw_GoogleReaderCell.frame.size.height + BOARDERHEIGHT;
        }
        
            [SVw_GoogleSelected setContentSize:CGSizeMake(0, m_DelCellAxisY-BOARDERHEIGHT+BOTTOMSAPCE)];
    }
    
    Tf_GoogleReaderSearch.delegate = self;
    
    //Recommended Feed
    SVw_RecommendedFeeds.hidden = NO;
    if([((AccountInfo *)[Array_AccountInfo objectAtIndex:0]).Array_ReFeed count] !=0) {
        
        int Axis_Y = 0;
        
        AddGoogleReaderCell *Vw_GoogleReaderCell;
        
        for (AccountRecommendedFeed *ReFeedOB in ((AccountInfo *)[Array_AccountInfo objectAtIndex:0]).Array_ReFeed) {
            
            //Check that Feed is selected.
            bool Check = false;
            if (Check==false) {
                
                Vw_GoogleReaderCell = [[[NSBundle mainBundle] loadNibNamed:@"AddGoogleReaderCell" owner:self options:nil] objectAtIndex:0];
                Vw_GoogleReaderCell.frame = CGRectMake(0, Axis_Y, Vw_GoogleReaderCell.frame.size.width, Vw_GoogleReaderCell.frame.size.height);
                
                Vw_GoogleReaderCell.Lab_GoogleReaderTitle.text = ReFeedOB.NS_Title;
                Vw_GoogleReaderCell.Lab_GoogleReaderWebLink.text = ReFeedOB.NS_Link;
                Vw_GoogleReaderCell.Lab_GoogleReaderContent.text = [NSString stringWithFormat:@"%@ - %@",ReFeedOB.NS_Content,ReFeedOB.NS_Link];
                
                //Set Font.
                [Vw_GoogleReaderCell.Lab_GoogleReaderTitle setFont:[UIFont fontWithName:@"EamesCenturyModern-Regular" size:11.5]];
                [Vw_GoogleReaderCell.Lab_GoogleReaderTitle setTextColor:[UIColor colorWithRed:108.0/255.0 green:109.0/255.0 blue:111.0/255.0 alpha:1.0]];
                [Vw_GoogleReaderCell.Lab_GoogleReaderContent setTextColor:[UIColor colorWithRed:163.0/255.0 green:163.0/255.0 blue:164.0/255.0 alpha:1.0]];
                
                //Set Action.
                [Vw_GoogleReaderCell.Bt_AddGoogleReader addTarget:self action:@selector(AddRecommendedFeedPressed:) forControlEvents:UIControlEventTouchUpInside];
                
                [SVw_RecommendedFeeds addSubview:Vw_GoogleReaderCell];
                
                Axis_Y = Axis_Y + Vw_GoogleReaderCell.frame.size.height + BOARDERHEIGHT;
            }
        }
        [SVw_RecommendedFeeds setContentSize:CGSizeMake(0, Axis_Y-BOARDERHEIGHT+BOTTOMSAPCE)];
    }
    
    if (self.BK_En_object.NonFirstUseCheck==FALSE) {
        
        Vw_FunctionAlertView = [[[NSBundle mainBundle] loadNibNamed:@"FunctionAlertView" owner:self options:nil] objectAtIndex:0];
        Vw_FunctionAlertView.frame = CGRectMake(Bt_Setting.center.x-FUNCTIONALERT_ARROW_AXIS_X,
                                                Bt_Setting.superview.frame.origin.y-Vw_FunctionAlertView.frame.size.height,
                                                Vw_FunctionAlertView.frame.size.width,
                                                Vw_FunctionAlertView.frame.size.height);
        Vw_FunctionAlertView.delegate = self;
        [Vw_FunctionAlertView setAlpha:0];
        
        [UIView animateWithDuration:0.5
                         animations:^{[Vw_FunctionAlertView setAlpha:1.0];[self.view addSubview:Vw_FunctionAlertView];}
                         completion:^(BOOL finished){ }];
        NonFirstCheck = FALSE;
        [self.BK_En_object setNonFirstCheck:TRUE];
    }
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}


-(IBAction)PasswordPressed:(id)sender {
    
    if(Vw_ChangePassword == nil)
    {
        [[NSBundle mainBundle] loadNibNamed:@"ChangePassword" owner:self options:nil];
        Vw_ChangePassword.frame = CGRectMake(0, 0, Vw_ChangePassword.frame.size.width, Vw_ChangePassword.frame.size.height);
        [Vw_ChangePassword.Bt_Cancel.titleLabel setFont:[UIFont fontWithName:@"EamesCenturyModern-Regular" size:11]];
        [Vw_ChangePassword.Bt_Done.titleLabel setFont:[UIFont fontWithName:@"EamesCenturyModern-Regular" size:11]];
        
        Vw_ChangePassword.delegate = self;
    }
    [Vw_ChangePassword setAlpha:0];
    
    [UIView animateWithDuration:0.5
                     animations:^{[Vw_ChangePassword setAlpha:1.0];[self.view addSubview:Vw_ChangePassword];}
                     completion:^(BOOL finished){ }];
}

-(IBAction)SignOutPressed:(id)sender {
    
    UIAlertView *AVw_Alert = [[UIAlertView alloc] initWithTitle:@"Alert"
                                                        message:@"Are you sure you want to Log out?"
                                                       delegate:self
                                              cancelButtonTitle:@"Cancel"
                                              otherButtonTitles:@"Ok",nil];
    AVw_Alert.tag = SignOut_Tag;
    AVw_Alert.delegate = self;
    [AVw_Alert show];
}

-(IBAction)showPhotoLib:(id)sender
{
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    picker.delegate = self;
    m_ProfileImageButton = ((UIButton *)sender).tag;
    
    Ctr_poper = [[UIPopoverController alloc] initWithContentViewController:picker];
    
    Ctr_poper.delegate = self;
    [Ctr_poper presentPopoverFromRect:((UIButton*)sender).frame inView:self.view permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];
}

-(IBAction)RecommendedFeedPressed:(id)sender {
    
    IVw_FeedStatus.image = [UIImage imageNamed:@"Tab_Recommended.png"];
    SVw_RecommendedFeeds.hidden = NO;
    Vw_SearchForFeeds.hidden = YES;
}

-(IBAction)SearchForFeedPressed:(id)sender {
    
    IVw_FeedStatus.image = [UIImage imageNamed:@"Tab_Search.png"];
    Vw_SearchForFeeds.hidden = NO;
    SVw_RecommendedFeeds.hidden = YES;
}

#pragma mark - Bottom Feature

-(IBAction)OpenMyStream:(id)sender {
    
    if (NonFirstCheck==FALSE)
        [self ConitunePressed:sender];
    else
        [self.delegate FeedSetViewControllerDelegateDidStream:self];
}

-(IBAction)OpenAccount:(id)sender {
    [self.delegate FeedSetViewControllerDelegateDidAccount:self];
}

-(IBAction)OpenMyBook:(id)sender {
    [self.delegate FeedSetViewControllerDelegateDidMyBooks:self];
}

-(IBAction)MyPhotoPressed:(id)sender {
    
    if (Vw_PhotoList == nil) {
        
        UIButton *Bt_Photo = (UIButton *)sender;
        
        Vw_PhotoList = [[[NSBundle mainBundle] loadNibNamed:@"SelectMyPhoto" owner:self options:nil] objectAtIndex:0];
        Vw_PhotoList.delegate = self;
        Vw_PhotoList.BK_En_object = self.BK_En_object;
        [Vw_PhotoList GetController:self UserInfo:self.Array_AccountInfo];
        Vw_PhotoList.frame = CGRectMake(Bt_Photo.frame.origin.x+Bt_Photo.frame.size.width/2-PHOTO_ARROW_AXIS_X,
                                        Bt_Photo.superview.frame.origin.y-Vw_PhotoList.frame.size.height,
                                        Vw_PhotoList.frame.size.width,
                                        Vw_PhotoList.frame.size.height);
    }
    
    [Vw_PhotoList setAlpha:0];
    [UIView animateWithDuration:0.5
                     animations:^{[Vw_PhotoList setAlpha:1.0];[self.view addSubview:Vw_PhotoList];}
                     completion:^(BOOL finished){ }];
}

-(IBAction)QuestionPressed:(id)sender {
    
    if (Vw_QuestionView == nil) {
        
        UIButton *Bt_Question = (UIButton *)sender;
        
        Vw_QuestionView = [[[NSBundle mainBundle] loadNibNamed:@"QuestionView" owner:self options:nil] objectAtIndex:0];
        Vw_QuestionView.frame = CGRectMake(Bt_Question.center.x-QUESTION_ARROW_AXIS_X,
                                           Bt_Question.superview.frame.origin.y-Vw_QuestionView.frame.size.height,
                                           Vw_QuestionView.frame.size.width,
                                           Vw_QuestionView.frame.size.height);
        
        Vw_QuestionView.delegate = self;
        [Vw_QuestionView Initialize];
    }
    
    [Vw_QuestionView setAlpha:0];
    [UIView animateWithDuration:0.5
                     animations:^{[Vw_QuestionView setAlpha:1.0];[self.view addSubview:Vw_QuestionView];}
                     completion:^(BOOL finished){ }];
}

#pragma mark - Segue

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    
    if([[segue identifier] isEqualToString:@"Instagram_Segue"]) {
        
        InstagramViewController *VC_Instagram = segue.destinationViewController;
        VC_Instagram.BK_En_object = self.BK_En_object;
        VC_Instagram.delegate = self;
    }
}

#pragma mark - Interface Orientation Management

//For iOS 5
-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
	return ((interfaceOrientation == UIInterfaceOrientationLandscapeLeft) || (interfaceOrientation == UIInterfaceOrientationLandscapeRight));
}

//For iOS 6
-(BOOL)shouldAutorotate {
    return YES;
}

-(NSUInteger)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskLandscape;
}

#pragma mark - Social Action

#pragma mark Facebook

-(IBAction)FacebookLogin:(id)sender
{
    if(SW_FaceBook.on)
    {
        //Facebook not first login.
        /**if ((BK_En_object.NS_FaceBookID!=nil)&&(BK_En_object.NS_FaceBookToken!=nil)) {
            
            [self.BK_En_object setFacebookONorOff:YES];
        }**/
        
        if ((BK_En_object.NS_FaceBookID!=nil)&&(BK_En_object.NS_FaceBookToken!=nil)) {
            
            [self.BK_En_object setFacebookONorOff:YES];
            return;
        }
        
        AppDelegate *BespokeAppDelegate = [[UIApplication sharedApplication] delegate];
        //if(!BespokeAppDelegate.session.isOpen)
        //{
            NSArray *permissions = [NSArray arrayWithObjects:
                                    @"user_photos",
                                    @"user_videos",
                                    @"publish_stream",
                                    @"offline_access",
                                    @"user_checkins",
                                    @"friends_checkins",
                                    @"email",
                                    @"user_location",
                                    @"read_stream", nil];
            
            FBSession *pSession = [[FBSession alloc] initWithAppID:@"250527955081918" permissions:permissions urlSchemeSuffix:nil tokenCacheStrategy:nil];
            BespokeAppDelegate.session = pSession;
        
            [BespokeAppDelegate.session openWithCompletionHandler:^(FBSession *session,
                                                                    FBSessionState status,
                                                                    NSError *error) {
                // and here we make sure to update our UX according to the new session state
                [self updateFBAPI];
            }];
        //}
    }else
        [BK_En_object setFacebookONorOff:NO];
}

-(void)updateFBAPI
{
    AppDelegate *beSpokeAppDelegate = [[UIApplication sharedApplication] delegate];
    
    FBRequest *me = [[FBRequest alloc] initWithSession:beSpokeAppDelegate.session graphPath:@"me"];
    
    [me startWithCompletionHandler:^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error)
     {
         //NSString *result = [NSString stringWithFormat:@"https://graph.facebook.com/%@/home?access_token=%@", user.id, beSpokeAppDelegate.session.accessToken];
         
         //if(beSpokeAppDelegate.session.isOpen)
         //{
         //NSLog(@"Facebook API Link = %@",result ) ;
         [self.BK_En_object setAccountInfoFaceBookID:user.id setFaceBookTotken:beSpokeAppDelegate.session.accessToken];
         [self.BK_En_object setFacebookONorOff:YES];
         /**}
         else {
             NSLog(@"Facebook Called Failed" ) ;
         }**/
     }];
}

#pragma mark Twitter

-(IBAction)TwitterLogin:(id)sender {
    
    if(SW_Twitter.on)
    {
        //[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=TWITTER"]];
        //[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"twitter://user?screen_name=a74121512"]];
        
        if ([self _checkForKeys] && [self _checkForLocalCredentials]) {
            //
            //  Step 1)  Ask Twitter for a special request_token for reverse auth
            //
            NSURL *url = [NSURL URLWithString:TW_OAUTH_URL_REQUEST_TOKEN];
            
            // "reverse_auth" is a required parameter
            NSDictionary *dict = [NSDictionary dictionaryWithObject:TW_X_AUTH_MODE_REVERSE_AUTH forKey:TW_X_AUTH_MODE_KEY];
            TWSignedRequest *signedRequest = [[TWSignedRequest alloc] initWithURL:url parameters:dict requestMethod:TWSignedRequestMethodPOST];
            
            [BK_En_object setTwitterONorOff:YES];
            [signedRequest performRequestWithHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                if (!data) {
                    [self showAlert:@"Unable to receive a request_token." title:@"Alert"];
                    [self _handleError:error forResponse:response];
                }
                else {
                    NSString *signedReverseAuthSignature = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                    
                    //
                    //  Step 2)  Ask Twitter for the user's auth token and secret
                    //           include x_reverse_auth_target=CK2 and x_reverse_auth_parameters=signedReverseAuthSignature parameters
                    //
                    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                        
                        NSDictionary *step2Params = [NSDictionary dictionaryWithObjectsAndKeys:[TWSignedRequest consumerKey], TW_X_AUTH_REVERSE_TARGET, signedReverseAuthSignature, TW_X_AUTH_REVERSE_PARMS, nil];
                        NSURL *authTokenURL = [NSURL URLWithString:TW_OAUTH_URL_AUTH_TOKEN];
                        TWRequest *step2Request = [[TWRequest alloc] initWithURL:authTokenURL parameters:step2Params requestMethod:TWRequestMethodPOST];
                        
                        //  Obtain the user's permission to access the store
                        //
                        //  NB: You *MUST* keep the ACAccountStore around for as long as you need an ACAccount around.  See WWDC 2011 Session 124 for more info.
                        self.accountStore = [[ACAccountStore alloc] init];
                        ACAccountType *twitterType = [self.accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
                        
                        [self.accountStore requestAccessToAccountsWithType:twitterType withCompletionHandler:^(BOOL granted, NSError *error) {
                            if (!granted) {
                                [BK_En_object setTwitterONorOff:NO];
                                [self showAlert:@"User rejected access to his/her account." title:@"Alert"];
                            }
                            else {
                                // obtain all the local account instances
                                NSArray *accounts = [self.accountStore accountsWithAccountType:twitterType];
                                
                                // we can assume that we have at least one account thanks to +[TWTweetComposeViewController canSendTweet], let's return it
                                [step2Request setAccount:[accounts objectAtIndex:0]];
                                [step2Request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
                                    // Thanks to Marc Delling for pointing out that we should check the status code below
                                    if (!responseData || ((NSHTTPURLResponse*)response).statusCode >= 400) {
                                        [BK_En_object setTwitterONorOff:NO];
                                        [self showAlert:@"Error occurred in Step 2.  Check console for more info." title:@"Alert"];
                                        [self _handleError:error forResponse:response];
                                    }
                                    else {
                                        NSString *responseStr = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
                                        [self _handleStep2Response:responseStr];
                                    }
                                }];
                            }
                        }];
                    });
                }
            }];
        }
    }
    else {
        [BK_En_object setTwitterONorOff:NO];
    }
}

- (void)showAlert:(NSString *)alert title:(NSString *)title
{
    //  This can be triggered from different threads, ensure that we keep it on the main queue
    dispatch_async(dispatch_get_main_queue(), ^{
        POP_ALERT(title, alert);
        
    });
}

/**
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1)
    {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=TWITTER"]];
    }
}**/


- (BOOL)_checkForKeys
{
    BOOL resp = YES;
    
    if (![TWSignedRequest consumerKey] || ![TWSignedRequest consumerSecret]) {
        [self showAlert:@"You must add reverse auth-enabled keys to TWSignedRequest.m" title:@"Alert"];
        resp = NO;
    }
    
    return resp;
}

- (BOOL)_checkForLocalCredentials
{
    BOOL resp = YES;
    
    if (![TWTweetComposeViewController canSendTweet]) {
        [self showAlert:@"Please configure a Twitter account in Settings." title:@"Alert"];
        resp = NO;
    }
    
    return resp;
}

- (void)_handleError:(NSError *)error forResponse:(NSURLResponse *)response
{
    NSHTTPURLResponse *urlResponse = (NSHTTPURLResponse *)response;
    
    NSLog(@"[Error]: %@", [error localizedDescription]);
    NSLog(@"[Error]: Response Code:%d \"%@\" ", [urlResponse statusCode], [NSHTTPURLResponse localizedStringForStatusCode:[urlResponse statusCode]]);
}

- (void)_handleStep2Response:(NSString *)responseStr
{
    NSDictionary *dict = [NSURL ab_parseURLQueryString:responseStr];
    
    // We are expecting a response dict of the format:
    //
    // {
    //     "oauth_token" = ...
    //     "oauth_token_secret" = ...
    //     "screen_name" = ...
    //     "user_id" = ...
    // }
    
    if ([dict count] == RESPONSE_EXPECTED_SIZE) {
        [BK_En_object setAccountInfoTwitterKey:[dict objectForKey:OAUTH_TOKEN] setTwitterSecret:[dict objectForKey:OAUTH_TOKEN_SECRET]];
        [BK_En_object setTwitterONorOff:YES];
    }
    else
        [self showAlert:@"The response doesn't seem correct.  Please check the console." title:@"Hmm..."];
}

#pragma mark Tumblr

-(IBAction)TumblrPressed:(id)sender {
    
    if (SW_Tumblr.on) {
        
        NSString *NS_Tumblr_Title;
        
        if (self.BK_En_object.NS_Tumblr!=nil) {
            NS_Tumblr_Title = [NSString stringWithFormat:@"Current blog name:\n%@",self.BK_En_object.NS_Tumblr];
            [BK_En_object setTumblrONorOff:YES];
        }
        else
            NS_Tumblr_Title = @"Please enter the name of the tumblr blog.";
        
        UIAlertView *AlertView = [[UIAlertView alloc]initWithTitle:NS_Tumblr_Title message:@"\n" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Ok", nil];
        [AlertView setTag:TUMBLR_ALERTVIEW_TAG];
        [AlertView show];
        
        UITextField *Tf_TumblrName = [[UITextField alloc] initWithFrame:CGRectMake(12,
                                                                                   ((UILabel *)[AlertView.subviews objectAtIndex:1]).frame.origin.y+
                                                                                   ((UILabel *)[AlertView.subviews objectAtIndex:1]).frame.size.height+10,
                                                                                   260,
                                                                                   25)];
        [Tf_TumblrName setBackgroundColor:[UIColor whiteColor]];
        [Tf_TumblrName setPlaceholder:@"  Tumblr Blog Name"];
        [Tf_TumblrName setTag:TUMBLR_TEXTFIELD_TAG];
        [Tf_TumblrName setReturnKeyType:UIReturnKeyGo];
        [AlertView addSubview:Tf_TumblrName];
    }
    else
        [BK_En_object setTumblrONorOff:NO];
}

#pragma mark Instagram

- (IBAction)InstagramLogin:(id)sender
{
    if(SW_Instagram.on) {
        
        [self performSegueWithIdentifier:@"Instagram_Segue" sender:self];
    }
    else
        [BK_En_object setInstagramONorOff:NO];
    
}

#pragma mark - GoogleReader

- (IBAction)SearchGoogleReaderPressed:(id)sender {
    
    if ([Tf_GoogleReaderSearch.text isEqualToString:@""]) {
        
        [Tf_GoogleReaderSearch resignFirstResponder];
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"Please enter a keyword." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [alertView show];
        return;
    }
    
    Lab_GoogleKeyword.text = [NSString stringWithFormat:KEYWORD_TITLE@"\"%@\"",Tf_GoogleReaderSearch.text];
    Lab_GoogleKeyword.hidden = NO;
    
    NSData *responseData =
    [RequestAPIFunction XML_PostRequest:[NSString stringWithFormat:@"<GoogleFeedSearch Keyword=\"%@\" />",[Tf_GoogleReaderSearch.text stringByReplacingOccurrencesOfString:@" " withString:@"%20"]] urlString:GOOGLEFEEDSEARCH_API];
    
    //No Network Connection or time out.
    if (responseData == nil) {
        
        [Tf_GoogleReaderSearch resignFirstResponder];
        return;
    }
    
    NSError *error;
    GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:responseData options:0 error:&error];
    
    //Restart GoogleResult.
    [SVw_GoogleResult removeFromSuperview];
    SVw_GoogleResult= [[UIScrollView alloc] initWithFrame:CGRectMake(SVw_GoogleResult.frame.origin.x,
                                                                     SVw_GoogleResult.frame.origin.y,
                                                                     SVw_GoogleResult.frame.size.width,
                                                                     SVw_GoogleResult.frame.size.height)];
    [Vw_SearchForFeeds addSubview:SVw_GoogleResult];
    
    int AddCellAxisY = 0;
    m_AddCellTagMax = 0;
    
    //No Results Found.
    if ([[[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding] rangeOfString:@"Error"].location != NSNotFound) {
        
        [Tf_GoogleReaderSearch resignFirstResponder];
        UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"No Results Found" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [alertView show];
        return;
    }
    
    //Get Feed from the XML
    NSArray *Array_GoogleFeedResult = [doc nodesForXPath:@"//GoogleFeedResult" error:nil];
    
    
    NSArray *Array_Feed = [[Array_GoogleFeedResult objectAtIndex:0]elementsForName:@"Feed"];
    
    
    //Parse XML.
    for (GDataXMLElement *entryElement in Array_Feed) {
        
        NSString *NS_title = [[[entryElement attributeForName:@"Title"] stringValue] StringParseSymbol];
        NSString *NS_content = [[[entryElement attributeForName:@"Content"] stringValue] StringParseSymbol];
        NSString *NS_href = [[entryElement attributeForName:@"Link"] stringValue];
        
        //Load UIView.
        AddGoogleReaderCell *Vw_Result = [[[NSBundle mainBundle] loadNibNamed:@"AddGoogleReaderCell" owner:self options:nil] objectAtIndex:0];
        Vw_Result.frame = CGRectMake(0, AddCellAxisY, Vw_Result.frame.size.width, Vw_Result.frame.size.height);
        
        Vw_Result.Lab_GoogleReaderTitle.text = NS_title;
        Vw_Result.Lab_GoogleReaderContent.text = NS_content;
        Vw_Result.Lab_GoogleReaderWebLink.text = NS_href;
        
        //Set Font.
        [Vw_Result.Lab_GoogleReaderTitle setFont:[UIFont fontWithName:@"EamesCenturyModern-Regular" size:11.5]];
        [Vw_Result.Lab_GoogleReaderTitle setTextColor:[UIColor colorWithRed:108.0/255.0 green:109.0/255.0 blue:111.0/255.0 alpha:1.0]];
        [Vw_Result.Lab_GoogleReaderContent setTextColor:[UIColor colorWithRed:163.0/255.0 green:163.0/255.0 blue:164.0/255.0 alpha:1.0]];
        
        //Set Tag.
        [Vw_Result setTag:m_AddCellTagMax+STARTING_ADDGOOGLEREADERCELL_TAG];
        [Vw_Result.Lab_GoogleReaderTitle setTag:m_AddCellTagMax+STARTING_ADDGOOGLEREADERCELL_TAG];
        [Vw_Result.Lab_GoogleReaderContent setTag:m_AddCellTagMax+STARTING_ADDGOOGLEREADERCELL_TAG];
        [Vw_Result.Lab_GoogleReaderWebLink setTag:m_AddCellTagMax+STARTING_ADDGOOGLEREADERCELL_TAG];
        [Vw_Result.Bt_AddGoogleReader setTag:m_AddCellTagMax+STARTING_ADDGOOGLEREADERCELL_TAG];
        [Vw_Result.Bt_icon setTag:m_AddCellTagMax+STARTING_ADDGOOGLEREADERCELL_TAG];
        
        [Vw_Result.Bt_AddGoogleReader addTarget:self action:@selector(AddGoogleReaderPressed:) forControlEvents:UIControlEventTouchUpInside];
        
        [SVw_GoogleResult addSubview:Vw_Result];
        
        AddCellAxisY = AddCellAxisY + Vw_Result.frame.size.height + BOARDERHEIGHT;
        m_AddCellTagMax++;
    }
    
    if (SVw_GoogleResult.frame.size.height<AddCellAxisY-BOARDERHEIGHT+BOTTOMSAPCE)
        [SVw_GoogleResult setContentSize:CGSizeMake(0, AddCellAxisY-BOARDERHEIGHT+BOTTOMSAPCE)];
    
    
    [Tf_GoogleReaderSearch resignFirstResponder];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    [self SearchGoogleReaderPressed:nil];
    
    return YES;
}

- (void)AddGoogleReaderPressed:(id)sender {
    
    AddGoogleReaderCell *Vw_GoogleReaderCell = (AddGoogleReaderCell *)[SVw_GoogleResult viewWithTag:[[sender superview] tag]];
    NSString *NS_Title = Vw_GoogleReaderCell.Lab_GoogleReaderTitle.text;
    NSString *NS_Content = Vw_GoogleReaderCell.Lab_GoogleReaderContent.text;
    NSString *NS_WebLink = Vw_GoogleReaderCell.Lab_GoogleReaderWebLink.text;
    
    //Check that Feed is selected.
    for (NSString *NS_CheckTitle in self.BK_En_object.Array_GoogleTitleSelected) {
        
        if ([NS_CheckTitle isEqualToString:NS_Title]) {
            
            int Google_tag = [self.BK_En_object.Array_GoogleTitleSelected indexOfObject:NS_CheckTitle];
            
            if  (([[self.BK_En_object.Array_GoogleContentSelected objectAtIndex:Google_tag] isEqualToString:NS_Content])&&
                ([[self.BK_En_object.Array_GoogleReaderLink objectAtIndex:Google_tag] isEqualToString:NS_WebLink])) {
                
                UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"This Feed Already Exists" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
                [alertView show];
                return;
            }
        }
    }
    
    //GoogleFeed add to BK_Enviroment
    [self.BK_En_object setAccountInfoGoogleReader:NS_Title SetContent:NS_Content SetWebLink:NS_WebLink];
    
    Vw_GoogleReaderCell.frame = CGRectMake(0, m_DelCellAxisY, Vw_GoogleReaderCell.frame.size.width, Vw_GoogleReaderCell.frame.size.height);
    [Vw_GoogleReaderCell setAlpha:0.0];
    [Vw_GoogleReaderCell.SW_GoogleReader setAlpha:1.0];
    Vw_GoogleReaderCell.Bt_icon.hidden = NO;
    Vw_GoogleReaderCell.Bt_AddGoogleReader.enabled = NO;
    
    //Set Action.
    [Vw_GoogleReaderCell.Bt_AddGoogleReader setImage:[UIImage imageNamed:@"Frame_Rss.png"] forState:UIControlStateNormal];
    [Vw_GoogleReaderCell.Bt_icon addTarget:self action:@selector(DelGoogleReaderPressed:) forControlEvents:UIControlEventTouchUpInside];
    [Vw_GoogleReaderCell.SW_GoogleReader addTarget:self action:@selector(SwitchPressed:) forControlEvents:UIControlEventValueChanged];
    
    //Animation.
    [UIView animateWithDuration:1.0
                     animations:^{[Vw_GoogleReaderCell setAlpha:1.0];[SVw_GoogleSelected addSubview:Vw_GoogleReaderCell];}
                     completion:^(BOOL finished){ }];
    
    [self SortCell:Vw_GoogleReaderCell
          SetIndex:[sender tag]
            SetTag:STARTING_ADDGOOGLEREADERCELL_TAG
         SetTagMax:m_AddCellTagMax
     SetScrollView:SVw_GoogleResult];
    
    //Modify Tag of Delete.
    [Vw_GoogleReaderCell.Lab_GoogleReaderTitle setTag:[BK_En_object.Array_GoogleTitleSelected count]-1+STARTING_DELGOOGLEREADERCELL_TAG];
    [Vw_GoogleReaderCell.Lab_GoogleReaderContent setTag:[BK_En_object.Array_GoogleTitleSelected count]-1+STARTING_DELGOOGLEREADERCELL_TAG];
    [Vw_GoogleReaderCell.Lab_GoogleReaderWebLink setTag:[BK_En_object.Array_GoogleTitleSelected count]-1+STARTING_DELGOOGLEREADERCELL_TAG];
    [Vw_GoogleReaderCell.Bt_AddGoogleReader setTag:[BK_En_object.Array_GoogleTitleSelected count]-1+STARTING_DELGOOGLEREADERCELL_TAG];
    [Vw_GoogleReaderCell.Bt_icon setTag:[BK_En_object.Array_GoogleTitleSelected count]-1+STARTING_DELGOOGLEREADERCELL_TAG];
    [Vw_GoogleReaderCell.SW_GoogleReader setTag:[BK_En_object.Array_GoogleTitleSelected count]-1+STARTING_DELGOOGLEREADERCELL_TAG];
    [Vw_GoogleReaderCell setTag:[BK_En_object.Array_GoogleTitleSelected count]-1+STARTING_DELGOOGLEREADERCELL_TAG];
    
    m_DelCellAxisY = m_DelCellAxisY + Vw_GoogleReaderCell.frame.size.height + BOARDERHEIGHT;
    
    if (SVw_GoogleSelected.frame.size.height<m_DelCellAxisY-BOARDERHEIGHT+BOTTOMSAPCE)
        [SVw_GoogleSelected setContentSize:CGSizeMake(0, m_DelCellAxisY-BOARDERHEIGHT+BOTTOMSAPCE)];
    
    m_AddCellTagMax--;
}

- (void)DelGoogleReaderPressed:(id)sender {
    
    AddGoogleReaderCell *Vw_GoogleReaderCell = (AddGoogleReaderCell *)((UIButton *)sender).superview;
    
    NSString *test = [NSString stringWithFormat:@"%@",Vw_GoogleReaderCell.Lab_GoogleReaderTitle.text];
    
    
    NSString *NS_DeleteCon = [NSString stringWithFormat:@"Do you really want to delete %@?",test];
    
    UIAlertView *AVw_Alert = [[UIAlertView alloc] initWithTitle:@"Are you sure?"
                                                        message:NS_DeleteCon
                                                       delegate:self
                                              cancelButtonTitle:@"Cancel"
                                              otherButtonTitles:@"Delete",nil];
    [AVw_Alert setTag:[[sender superview] tag]];
    AVw_Alert.delegate = self;
    [AVw_Alert show];
}

#pragma mark - RecommendedFeed

- (void)AddRecommendedFeedPressed:(id)sender {
    
    AddGoogleReaderCell *Vw_Cell = (AddGoogleReaderCell *)((UIButton *)sender).superview;
    NSString *NS_Title = Vw_Cell.Lab_GoogleReaderTitle.text;
    NSString *NS_Content = Vw_Cell.Lab_GoogleReaderContent.text;
    NSString *NS_WebLink = Vw_Cell.Lab_GoogleReaderWebLink.text;
    
    //Check that Feed is selected.
    for (NSString *NS_CheckWebLink in self.BK_En_object.Array_GoogleReaderLink) {
        
        if ([NS_CheckWebLink isEqualToString:NS_WebLink]) {
            
            int Google_tag = [self.BK_En_object.Array_GoogleReaderLink indexOfObject:NS_CheckWebLink];
            
            if  (([[self.BK_En_object.Array_GoogleTitleSelected objectAtIndex:Google_tag] isEqualToString:NS_Title])&&
                 ([[self.BK_En_object.Array_GoogleContentSelected objectAtIndex:Google_tag] isEqualToString:NS_Content])) {
                
                UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"This Feed Already Exists" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
                [alertView show];
                return;
            }
        }
    }
    
    AddGoogleReaderCell *Vw_GoogleReaderCell = [[[NSBundle mainBundle] loadNibNamed:@"AddGoogleReaderCell" owner:self options:nil] objectAtIndex:0];
    Vw_GoogleReaderCell.Lab_GoogleReaderTitle.text = NS_Title;
    Vw_GoogleReaderCell.Lab_GoogleReaderContent.text = NS_Content;
    Vw_GoogleReaderCell.Lab_GoogleReaderWebLink.text = NS_WebLink;
    
    //GoogleFeed add to BK_Enviroment
    [self.BK_En_object setAccountInfoGoogleReader:NS_Title SetContent:NS_Content SetWebLink:NS_WebLink];
    
    Vw_GoogleReaderCell.frame = CGRectMake(0, m_DelCellAxisY, Vw_GoogleReaderCell.frame.size.width, Vw_GoogleReaderCell.frame.size.height);
    [Vw_GoogleReaderCell setAlpha:0.0];
    [Vw_GoogleReaderCell.SW_GoogleReader setAlpha:1.0];
    Vw_GoogleReaderCell.Bt_icon.hidden = NO;
    Vw_GoogleReaderCell.Bt_AddGoogleReader.enabled = NO;
    

    //Set Font.
    [Vw_GoogleReaderCell.Lab_GoogleReaderTitle setFont:[UIFont fontWithName:@"EamesCenturyModern-Regular" size:11.5]];
    [Vw_GoogleReaderCell.Lab_GoogleReaderTitle setTextColor:[UIColor colorWithRed:108.0/255.0 green:109.0/255.0 blue:111.0/255.0 alpha:1.0]];
    [Vw_GoogleReaderCell.Lab_GoogleReaderContent setTextColor:[UIColor colorWithRed:163.0/255.0 green:163.0/255.0 blue:164.0/255.0 alpha:1.0]];
    
    //Set Action.
    [Vw_GoogleReaderCell.Bt_AddGoogleReader setImage:[UIImage imageNamed:@"Frame_Rss.png"] forState:UIControlStateNormal];
    [Vw_GoogleReaderCell.Bt_icon addTarget:self action:@selector(DelGoogleReaderPressed:) forControlEvents:UIControlEventTouchUpInside];
    [Vw_GoogleReaderCell.SW_GoogleReader addTarget:self action:@selector(SwitchPressed:) forControlEvents:UIControlEventValueChanged];
    
    //Animation.
    [UIView animateWithDuration:1.0
                     animations:^{[Vw_GoogleReaderCell setAlpha:1.0];[SVw_GoogleSelected addSubview:Vw_GoogleReaderCell];}
                     completion:^(BOOL finished){ }];
    
    [Vw_GoogleReaderCell setTag:[BK_En_object.Array_GoogleTitleSelected count]-1+STARTING_DELGOOGLEREADERCELL_TAG];
    
    m_DelCellAxisY = m_DelCellAxisY + Vw_GoogleReaderCell.frame.size.height + BOARDERHEIGHT;
    
    if (SVw_GoogleSelected.frame.size.height<m_DelCellAxisY-BOARDERHEIGHT+BOTTOMSAPCE)
        [SVw_GoogleSelected setContentSize:CGSizeMake(0, m_DelCellAxisY-BOARDERHEIGHT+BOTTOMSAPCE)];
}

#pragma mark - SwitchPressed

- (void)SwitchPressed:(id)sender {
    
    if (((UISwitch *)sender).on)
        [BK_En_object setGoogleSwitchCheck:1 SetIndex:((UISwitch *)sender).superview.tag-STARTING_DELGOOGLEREADERCELL_TAG];
    else if (!((UISwitch *)sender).on)
        [BK_En_object setGoogleSwitchCheck:0 SetIndex:((UISwitch *)sender).superview.tag-STARTING_DELGOOGLEREADERCELL_TAG];
}

#pragma mark - Calculate Sort

- (void)SortCell:(AddGoogleReaderCell *)GoogleReaderCell SetIndex:(int)Index SetTag:(int)Starting_CellTag SetTagMax:(int)TagMax SetScrollView:(UIScrollView *)SVw_Google {
    int CellAxisY_TEMP = 0;
    
    //Calculate AXIS_Y.
    for (int i=Starting_CellTag; i<Index; i++) {
        CellAxisY_TEMP = CellAxisY_TEMP+GoogleReaderCell.frame.size.height+BOARDERHEIGHT;
    }
    
    for (int i=Index+1; i<TagMax+Starting_CellTag+1; i++) {
        
        AddGoogleReaderCell *Vw_AddGoogleReaderCell = (AddGoogleReaderCell *)[SVw_Google viewWithTag:i];
        
        //Animation.
        [UIView beginAnimations:nil context:NULL];
        [UIView setAnimationDuration:1.0];
        [UIView setAnimationBeginsFromCurrentState:YES];
        if (SVw_Google==SVw_GoogleResult)
            Vw_AddGoogleReaderCell.frame = CGRectMake(0, CellAxisY_TEMP, Vw_AddGoogleReaderCell.frame.size.width, Vw_AddGoogleReaderCell.frame.size.height);
        else if (SVw_Google==SVw_GoogleSelected)
            Vw_AddGoogleReaderCell.frame = CGRectMake(0, GoogleFeed_TOP_AXIS_Y+CellAxisY_TEMP, Vw_AddGoogleReaderCell.frame.size.width, Vw_AddGoogleReaderCell.frame.size.height);
        [UIView commitAnimations];
        
        //Modify Tag.
        [Vw_AddGoogleReaderCell.Lab_GoogleReaderTitle setTag:i-1];
        [Vw_AddGoogleReaderCell.Lab_GoogleReaderContent setTag:i-1];
        [Vw_AddGoogleReaderCell.Lab_GoogleReaderWebLink setTag:i-1];
        [Vw_AddGoogleReaderCell.Bt_AddGoogleReader setTag:i-1];
        [Vw_AddGoogleReaderCell.Bt_icon setTag:i-1];
        [Vw_AddGoogleReaderCell.SW_GoogleReader setTag:i-1];
        [Vw_AddGoogleReaderCell setTag:i-1];
        
        CellAxisY_TEMP = CellAxisY_TEMP +Vw_AddGoogleReaderCell.frame.size.height+BOARDERHEIGHT;
    }
    
    if (SVw_Google==SVw_GoogleResult)
        [SVw_Google setContentSize:CGSizeMake(0, CellAxisY_TEMP-BOARDERHEIGHT-BOARDERHEIGHT+BOTTOMSAPCE)];
}

#pragma mark - 

- (void)uiViewTouched_FunctionAlert:(BOOL)wasInSide {
    
    if (!wasInSide)
        [Vw_FunctionAlertView removeFromSuperview];
}

#pragma mark - UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    
    //SignOut Pressed.
    if ((buttonIndex==1)&&(alertView.tag==SignOut_Tag)) {
        
        NSString *XML_Facebook = @"";
        NSString *XML_Twitter = @"";
        NSString *XML_Tumblr = @"";
        NSString *XML_Instagram = @"";
        
        [NSThread detachNewThreadSelector:@selector(threadStartAnimating) toTarget:self withObject:nil];
        
        if (BK_En_object.NS_FaceBookID!=nil)
            XML_Facebook = [NSString stringWithFormat:@"<Facebook ID=\"%@\" Token=\"%@\" Switch=\"%d\" />",
                            BK_En_object.NS_FaceBookID,
                            BK_En_object.NS_FaceBookToken,
                            BK_En_object.FacebookFeedCheck];
        
        if (BK_En_object.NS_OauthKey!=nil)
            XML_Twitter = [NSString stringWithFormat:@"<Twitter Key=\"%@\" Secret=\"%@\" Switch=\"%d\" />",
                           BK_En_object.NS_OauthKey,
                           BK_En_object.NS_OauthSecret,
                           BK_En_object.TwitterFeedCheck];
        
        if (BK_En_object.NS_Tumblr!=nil)
            XML_Tumblr = [NSString stringWithFormat:@"<Tumblr Name=\"%@\" Switch=\"%d\" />",
                          BK_En_object.NS_Tumblr,
                          BK_En_object.TumblrFeedCheck];
        
        if (BK_En_object.NS_InstagramToken!=nil)
            XML_Instagram = [NSString stringWithFormat:@"<Instagram Token=\"%@\" Switch=\"%d\" />",
                             BK_En_object.NS_InstagramToken,
                             BK_En_object.InstagramFeedCheck];
        
        
        NSMutableString *XML_GoogleReader = [NSMutableString string];
        
        for (NSString *NS_GoogleTitle in self.BK_En_object.Array_GoogleTitleSelected) {
            int index = [self.BK_En_object.Array_GoogleTitleSelected indexOfObject:NS_GoogleTitle];
            
            NSString *NS_GoogleContent = [self.BK_En_object.Array_GoogleContentSelected objectAtIndex:index];
            NSString *NS_GoogleLink = [self.BK_En_object.Array_GoogleReaderLink objectAtIndex:index];
            int GoogleSwitch = [[self.BK_En_object.Array_GoogleSwitchCheck objectAtIndex:index] intValue];
            
            [XML_GoogleReader appendString:[NSString stringWithFormat:@"<GoogleFeed Title=\"%@\" Content=\"%@\" Link=\"%@\" Switch=\"%d\" />",
                                            NS_GoogleTitle,
                                            NS_GoogleContent,
                                            NS_GoogleLink,
                                            GoogleSwitch]];
        }
        
        if (BK_En_object.NS_Calendar==nil)
            BK_En_object.NS_Calendar = @"";
        
        if (BK_En_object.NS_Channel==nil)
            BK_En_object.NS_Channel = @"";
        
        NSData *responseData =
        [RequestAPIFunction XML_PostRequest:[NSString stringWithFormat:@"<Account UserName=\"%@\" Channel=\"%@\" WeddingDate=\"%@\">%@%@%@%@%@</Account>",
                                             BK_En_object.userName,
                                             BK_En_object.NS_Channel,
                                             BK_En_object.NS_Calendar,
                                             XML_Facebook,
                                             XML_Twitter,
                                             XML_Tumblr,
                                             XML_Instagram,
                                             [XML_GoogleReader stringByReplacingOccurrencesOfString:@"&" withString:@"&amp;"]]
                                  urlString:UPLOADACCOUNTINFO_API];
        
        //No Network Connection or time out.
        if (responseData == nil)
            return;
        
        [BK_En_object clearEnviroment];
        
        //Clear Instagram cookie.
        NSString *kDialogBaseURL = @"https://instagram.com/";
        NSHTTPCookieStorage* cookies = [NSHTTPCookieStorage sharedHTTPCookieStorage];
        NSArray* instagramCookies = [cookies cookiesForURL:[NSURL URLWithString:kDialogBaseURL]];
        
        for (NSHTTPCookie* cookie in instagramCookies)
            [cookies deleteCookie:cookie];
        
        [self.delegate FeedSetViewControllerDelegateDidLogoScreen:self];
        
        [NSThread detachNewThreadSelector:@selector(threadStopAnimating) toTarget:self withObject:nil];
    }
    else {
        
        //Tumblr Alert.
        if (alertView.tag==TUMBLR_ALERTVIEW_TAG) {
            NSLog(@"%@",((UITextField *)[alertView viewWithTag:TUMBLR_TEXTFIELD_TAG]).text);
            if ((![((UITextField *)[alertView viewWithTag:TUMBLR_TEXTFIELD_TAG]).text isEqualToString:@""])&&(((UITextField *)[alertView viewWithTag:TUMBLR_TEXTFIELD_TAG]).text!=nil)&&(buttonIndex==1)) {
                [self.BK_En_object setAccountInfoTumblr:((UITextField *)[alertView viewWithTag:TUMBLR_TEXTFIELD_TAG]).text];
                [BK_En_object setTumblrONorOff:YES];
            }
            else {
                [BK_En_object setTumblrONorOff:NO];
                self.SW_Tumblr.on = false;
            }
            return;
        }
        
        //Google Feed Alert.
        if (buttonIndex==1) {
            
            AddGoogleReaderCell *Vw_GoogleReaderCell = (AddGoogleReaderCell *)[SVw_GoogleSelected viewWithTag:[alertView tag]];
            
            [self SortCell:Vw_GoogleReaderCell
                  SetIndex:[alertView tag]
                    SetTag:STARTING_DELGOOGLEREADERCELL_TAG
                 SetTagMax:[BK_En_object.Array_GoogleTitleSelected count]
             SetScrollView:SVw_GoogleSelected];
            
            [Vw_GoogleReaderCell removeFromSuperview];
            
            //Remove Google feed in BK.
            [BK_En_object setGoogleDelete:[alertView tag]-STARTING_DELGOOGLEREADERCELL_TAG];
            
            NSLog(@"BK_Del:%@",BK_En_object.Array_GoogleReaderLink);
            NSLog(@"BK_Del:%@",BK_En_object.Array_GoogleSwitchCheck);
            
            m_DelCellAxisY = m_DelCellAxisY - Vw_GoogleReaderCell.frame.size.height - BOARDERHEIGHT;
            
            [SVw_GoogleSelected setContentSize:CGSizeMake(0, m_DelCellAxisY)];
            
        }
        else {
            
            AddGoogleReaderCell *Vw_GoogleReaderCell = (AddGoogleReaderCell *)[SVw_GoogleSelected viewWithTag:[alertView tag]];
            [Vw_GoogleReaderCell.Bt_icon setImage:[UIImage imageNamed:@"btn_RSSDel.png"] forState:UIControlStateNormal];
        }
    }
}


#pragma mark - ChangePasswordDelegate

- (void)CancelPressed_ChangePassword {
    
    Vw_ChangePassword.Tf_NewPassword.text = nil;
    Vw_ChangePassword.Tf_ConfirmPassword.text = nil;
    [Vw_ChangePassword removeFromSuperview];
}

#pragma mark - UIImagePickerControllerDelegate

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo
{
    [self.Ctr_poper dismissPopoverAnimated:true];
    
    UIImage *resizedImg = [image imageByScalingAndCroppingForSize:CGSizeMake(self.Bt_yourPhoto.frame.size.width, self.Bt_yourPhoto.frame.size.height)];
    
    if(m_ProfileImageButton == 101)
    {
        [Bt_yourPhoto setImage:resizedImg forState:UIControlStateNormal];
        [BK_En_object setAccountYourImage:resizedImg];
    }
    
}

#pragma mark - SelectMyPhotoDelegate

-(void) uiViewTouched_SelectMyPhoto:(BOOL)wasInSide {
    if(!wasInSide)
        [Vw_PhotoList removeFromSuperview];
}

- (void)PhotoSaveSuccess:(NSString *)BoardName {
    
    [Vw_PhotoList removeFromSuperview];
    
    NSString *NS_Message = [NSString stringWithFormat:@"Great! This photo has been clipped to your \"%@\" Books",BoardName];
    
    UIAlertView *AlertView = [[UIAlertView alloc]initWithTitle:@"Success" message:NS_Message delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
    
    [AlertView show];
}

#pragma mark - InstagramViewControllerDelegate

-(void)InstagramViewControllerDelegateDidClose:(InstagramViewController *)controller
{
    [self dismissViewControllerAnimated:YES completion:nil];
    
    if(BK_En_object.InstagramFeedCheck !=NO)
        SW_Instagram.on = TRUE;
    else
        SW_Instagram.on = FALSE;
}

#pragma mark - QuestionViewDelegate

- (void)uiViewTouched_Question:(BOOL)wasInSide {
    
    if(!wasInSide)
        [Vw_QuestionView removeFromSuperview];
}

#pragma mark - LoadingUI

-(void)threadStartAnimating {
    
    [self.view addSubview:[LoadingUI LoadingView:self.view.bounds.size.width SetHeight:self.view.bounds.size.height]];
    [self.view addSubview:[LoadingUI LoadingImage:self.view.bounds.size.width SetHeight:self.view.bounds.size.height]];
}

-(void)threadStopAnimating {
    
    [[NSOperationQueue mainQueue] addOperationWithBlock:
     ^(void) {
         [[self.view viewWithTag:LOADINGVIEW_TAG] removeFromSuperview];
         [[self.view viewWithTag:LOADINGIMAGE_TAG] removeFromSuperview];
     }];
}

@end